<template>
  <continer :isNoTabs="true" class="agentMonitoring">
    <template slot="search">
      <QuickSearch
        :advForm="quickSearchForm"
        @QuickSearch="handleSearchFunc"
      ></QuickSearch>
    </template>
    <template slot="oprate">
      <!-- <el-button size="mini" @click="reset">重置</el-button> -->
      <el-button type="primary" size="mini" @click="handleSearchFunc">查询</el-button>
      <el-button size="mini" @click="edit({}, 'add')" v-functions="['customer_config_filter_insert']">新增</el-button>
    </template>
    <template slot="content">
      <!-- 表格 -->
      <configTable
        ref="table"
        :headers="tableHeaders"
        :data="tableData"
        :pagingData="pagingData"
        @pageChange="handleCurrentChange"
        @pageSizeChange="handleSizeChange"
        @checkHeadersChange="checkHeadersChange"
        :headersConfig="false"
      >
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
              v-if="
                item.show &&
                !['oprate', 'enabled', 'category'].includes(item.prop)
              "
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :sortable="item.sortable"
              :show-overflow-tooltip="true"
              :min-width="item.width || 80"
            >
            </u-table-column>
            <u-table-column
              v-if="item.prop === 'category'"
              :key="index"
              :label="item.label"
              :width="80"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.category | getCategoryType }}</span>
              </template>
            </u-table-column>
            <u-table-column
              v-if="item.prop === 'enabled'"
              :key="index"
              :label="item.label"
              :width="80"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.enabled" v-functions="['customer_config_filter_enable']"><i class="V7_iconfont V7_iconV7tubiao_dian enable-span"></i>启用</span>
                <span v-else v-functions="['customer_config_filter_enable']"><i class="V7_iconfont V7_iconV7tubiao_dian disable-span"></i>停用</span>
              </template>
            </u-table-column>
            <u-table-column
              v-if="item.show && item.prop === 'oprate'"
              :key="index"
              :label="item.label"
              :resizable="false"
              fixed="right"
            >
              <template slot-scope="scope">
                <span class="oprate-span" v-if="scope.row.category !== 'system'" @click="enableOrDisable(scope.row)">{{scope.row.enabled ? '停用': '启用'}}</span>
                <span class="oprate-span" v-functions="['customer_config_filter_edit']" @click="edit(scope.row, 'edit')">编辑</span>
                <span class="oprate-span red-span" v-if="scope.row.category !== 'system'" v-functions="['customer_config_filter_delete']" @click="remove(scope.row)">删除</span>
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
      <EditFilter ref="EditFilter" @refresh="getData"></EditFilter>
    </template>
  </continer>
</template>

<script lang="ts">
/**
 * 客户过滤器
 */
import { Component, Vue, Ref } from 'vue-property-decorator'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import configTable from '@/components/globalTool/resizeTable/index.vue'
import { commonAction } from '@/utils/common'
import { CommonModule } from '@/store/modules/common'
import EditFilter from './EditFilter.vue'
@Component({
  name: 'NoticeSetting',
  components: {
    QuickSearch,
    configTable,
    continer,
    EditFilter
  },
  filters: {
    getCategoryType (type) {
      if (type === 'system') {
        return '系统预置'
      } else if (type === 'custom') {
        return '自定义'
      } else {
        return '未知分类'
      }
    }
  }
})
export default class NoticeSetting extends Vue {
  @Ref() private readonly EditFilter
  [x: string]: any
  private tableData: any = []
  private pagingData: any = { total: 0, limit: 10, page: 1 }
  private checkHeaders: [] = []
  private quickSearchForm: any = {}

  // 座席列表
  get AgentList () {
    return (CommonModule as any).publicCache.userList.map(v => ({ name: `${v.agentName} 【${v.agentNumber}】`, _id: v._id }))
  }

  // 初始化搜索条件
  private async getSelectData () {
    this.quickSearchForm = {
      form: {
        name: ''
      },
      advSearchOptions: [
        { label: '过滤器名称', name: 'name', inputType: 'input', clearable: true, placeholder: '请选择' }
      ]
    }
  }

  // // 重置
  // private reset () {
  //   this.quickSearchForm.form = {
  //     name: ''
  //   }
  //   this.handleSearchFunc()
  // }

  private async mounted () {
    this.getSelectData()
    this.getData()
  }

  // 获取数据
  private async getData () {
    let actionData: any = {
      limit: this.pagingData.limit,
      page: this.pagingData.page
    }
    actionData = { ...actionData, ...this.quickSearchForm.form }
    const resData: any = await commonAction({ url: '/server-crm/action/config/customer/filter/list', method: 'POST', data: actionData })
    if (resData.success && resData.data) {
      const resList = resData.data.list || []
      const count = resData.data.count || 0
      if (resList.length === 0) {
        const page = Math.ceil(count / this.pagingData.limit)
        if (!count) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
          this.pagingData.page = 1
        } else { // 删除到最后一个回到上一页
          this.pagingData.page = page
          this.getData()
          return false
        }
      }
      resList.forEach((item: any) => {
        const agentObj = this.$store.state.common.publicCache.userListObj[item.updateUser]
        item.updateAgent = agentObj ? `${agentObj.agentName}【${agentObj.agentNumber}】` : '--'
      })
      this.tableData = resList
      this.pagingData.total = count
    }
  }

  // 搜索
  private handleSearchFunc () {
    this.pagingData.page = 1
    this.getData()
  }

  // 初始化表头
  private tableHeaders: object[] = [
    { label: '过滤器名称', prop: 'name' },
    { label: '分类', prop: 'category' },
    { label: '创建时间', prop: 'createTime' },
    { label: '更新时间', prop: 'updateTime' },
    { label: '更新人', prop: 'updateAgent' },
    { label: '状态', prop: 'enabled' },
    { label: '操作', prop: 'oprate', disenable: true }
  ]

  private checkHeadersChange (checkList) {
    this.$set(this, 'checkHeaders', checkList)
  }

  private handleSizeChange (size: number) {
    this.pagingData.limit = size
    this.handleSearchFunc()
  }

  private handleCurrentChange (page: number) {
    this.pagingData.page = page
    this.getData()
  }

  // 停用或启用
  private enableOrDisable (item: any) {
    this.$confirm(`请确认是否 ${item.enabled ? '启用' : '停用'}【 ${item.name} 】？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const actionData = item
      actionData.enabled = !actionData.enabled
      commonAction({ url: '/server-crm/action/config/customer/filter/update', method: 'post', data: actionData }).then(res => {
        if (res.success) {
          this.$message.success(`${item.enabled ? '停用' : '启用'} 成功`)
          this.getData()
        }
      })
    }).catch(() => {
      console.log('取消===')
    })
  }

  // 编辑过滤器
  private edit (item, type) {
    this.EditFilter.openDraw(item, type)
  }

  // 删除过滤器
  private remove (item: any) {
    this.$confirm(`请确认是否删除【${item.name}】？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      commonAction({ url: '/server-crm/action/config/customer/filter/delete', method: 'post', data: { _id: item._id } }).then(res => {
        if (res.success) {
          this.$message.success('删除成功')
          this.getData()
        }
      })
    }).catch(() => {
      console.log('取消===')
    })
  }
}
</script>
<style lang="stylus" scoped>
.oprate-span
  cursor pointer
  color $c-main
  margin 0 4px
.red-span, .disable-span
  color $c-danger
.enable-span
  color $c-green
  font-size 12px
</style>
